import axios from 'axios';
import { Loading, Message } from 'element-ui';
import { baseUrl, baseApi, token } from '@/utils/config/index.js';

axios.defaults.timeout = 60000;
axios.defaults.headers.post['Content-Type'] = 'multipart/json;charset=UTF-8;';

const service = axios.create({
	baseURL: baseUrl + baseApi, // url = base api url + request url
})

let loading = '';

// 请求拦截
service.interceptors.request.use((config) => {
	config.headers.token = token;

	// 不传递默认开启loading
	if (!config.hideloading) {
		// loading
		loading = Loading.service({
			fullscreen: true,
			lock: true,
			text: config.loadingText || '',
		});
	}

	return config;
},
	(error) => {
		console.log('err>>>>>>>', error) // for debug
		return Promise.error(error);
	});

// 响应的拦截
service.interceptors.response.use((res) => {
	if (res.status === 200) {
		if (res.data.success) {
			loading && loading.close();

			return Promise.resolve(res.data);
		} else {
			loading && loading.close();
			Message.error(`${res.data.msg}`);

			return Promise.resolve(res.data);
		}
	} else {
		loading && loading.close();
		Message.error(`请求错误`);

		return Promise.reject(res);
	}
}, (err) => {
	loading && loading.close();
	Message.error('请求错误');
	console.log('err>>>>>>>', err) // for debug

	return Promise.reject(err)
});

export default service
